// src/router/index.ts
import { createRouter, createWebHashHistory, createWebHistory, type RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/layout.vue'

import 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    title?: string
    icon?: string
  }
}

// 自动扫描 Demo/components 目录下的所有 .vue 文件
const demoModules = import.meta.glob('@/pages/demo/components/*.vue')
// console.log('demoModules: ', demoModules);

const demoChildren: RouteRecordRaw[] = Object.entries(demoModules).map(([path, component]) => {
  const name = path.match(/\/([^/]+)\.vue$/)?.[1] || 'unknown'
  return {
    path: name.toLowerCase(),
    name: `${name}`,
    meta: {
      title: name,
    },
    component,
  }
})

// demoChildren.unshift({
//   path: 'demoIndex',
//   name: 'DemoIndex',
//   component: () => import('@/pages/demo/components/demo.vue'),
// } as any)

console.log('demoChildren: ', demoChildren);

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        meta: {
          title: '首页',
          icon: 'home'
        },
        component: () => import('@/pages/home/home.vue'),
      },
      {
        path: '/about',
        name: 'About',
        meta: {
          title: '关于',
          icon: 'about'
        },
        component: () => import('@/pages/about/about.vue'),
      },
      {
        path: '/demo',
        name: 'Demo',
        meta: {
          title: '示例',
          icon: 'demo'
        },
        // component: () => import('@/pages/demo/demo.vue'),
        redirect: 'AdemoIndex',
        children: demoChildren, // 自动生成的子路由
      },
      {
        path: '/user',
        name: 'User',
        meta: {
          title: '用户',
          icon: 'user'
        },
        // component: () => import('@/pages/user/user.vue'),
        redirect: '/user/userSet',
        children: [
          {
            path: '/user/userSet',
            name: 'UserSet',
            meta: {
              title: '用户设置',
              icon: 'userSet'
            },
            component: () => import('@/pages/user/components/userSet.vue'),
          }
        ]
      }
    ],
  },
]

const router = createRouter({
  // history: createWebHistory(), // history 模式
  history: createWebHashHistory(), // hash 模式
  routes
})

export default router
